import { GetcoursewarePage, SearchCourseware } from "@/api/lms";
import { type PaginationProps } from "@pureadmin/table";
import { reactive, ref, computed, onMounted } from "vue";
import { useLmsStoreHook } from "@/store/modules/lms";

const lmsStore = useLmsStoreHook();

export function useCourse() {
  const courseFormRef = ref();
  const form = reactive({
    name: "",
    folderId: ""
  });
  const dataList = ref([]);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      type: "selection",
      width: 55,
      align: "left",
      hide: ({ checkList }) => checkList.includes("勾选列")
    },
    {
      label: "序号",
      type: "index",
      width: 70,
      hide: ({ checkList }) => !checkList.includes("序号列")
    },
    {
      label: "课程编号",
      prop: "code",
      minWidth: 130
    },
    {
      label: "课程名称",
      prop: "name",
      minWidth: 130
    },
    {
      label: "封面",
      prop: "label"
    },
    {
      label: "操作",
      fixed: "right",
      width: 80,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });

  function handleAdd(row) {
    console.log(row);
    lmsStore.pickCourseware.push(row);
  }

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch() {
    loading.value = true;
    const p: SearchCourseware = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      name: form.name,
      folderId: form.folderId
    };
    const { list, total } = await GetcoursewarePage(p);
    dataList.value = list;
    pagination.total = total;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  onMounted(() => {
    onSearch();
  });

  return {
    courseFormRef,
    form,
    loading,
    columns,
    dataList,
    pagination,
    buttonClass,
    onSearch,
    resetForm,
    handleAdd,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
